package cm.example.shoppingplatformspringboot.service;

import cm.example.shoppingplatformspringboot.entity.Address;
import cm.example.shoppingplatformspringboot.mapper.AddressMapper;
import jakarta.annotation.Resource;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AddressService {
    @Resource
    private AddressMapper addressMapper;
    private static final Logger logger = LoggerFactory.getLogger(AddressService.class);

    // 新增：获取用户的所有地址
    public List<Address> getUserAddresses(Long userId) {
        return addressMapper.findByUserId(userId);
    }

    // 新增：添加地址
    @Transactional // 添加事务注解，保证数据一致性
    public int addAddress(@NotNull Address address) {
        Long userId = address.getUser_id();
        // 如果前端明确要求设为默认
        if ("Y".equals(address.getDef())) {
            // 取消该用户所有现有地址的默认状态
            addressMapper.setDefaultAddress(userId);
            address.setDef("Y");
        } else {
            // 如果用户没有地址，自动设为默认
            List<Address> existingAddresses = addressMapper.findByUserId(userId);
            address.setDef(existingAddresses.isEmpty() ? "Y" : "N");
        }
        return addressMapper.insertAddress(address);
    }

    // 新增：更新地址
    @Transactional // 添加事务注解
    public int updateAddress(@NotNull Address address) {
        if ("Y".equals(address.getDef())) {
            addressMapper.cancelOtherDefaultAddresses(address.getUser_id(), address.getId());
        }
        return addressMapper.updateAddress(address);
    }

    // 新增：删除地址
    @Transactional
    public int deleteAddress(Long id) {
        try {
            return addressMapper.deleteAddress(id);
        } catch (Exception e) {
            logger.error("删除地址失败", e);
            return 0;
        }
    }
}